package com.sam;

import java.util.HashMap;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.google.appengine.api.datastore.KeyFactory;
import com.opensymphony.xwork2.ActionSupport;
import com.sam.entities.Cap;
import com.sam.utils.EMF;

public class GuardarDatos extends ActionSupport implements ServletRequestAware,
		ServletResponseAware {

	private static final long serialVersionUID = 5143151927405515069L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	public String execute() throws Exception {
		String capId = getServletRequest().getParameter("capId");

		EntityManager em = EMF.get().createEntityManager();

		Cap cap = (Cap) em
				.createQuery("Select From Cap Where key = :key")
				.setParameter("key",
						KeyFactory.createKey("Cap", Long.parseLong(capId)))
				.getSingleResult();
		
		/*Map<String, String> descripcion = cap.getDescripcion();
		if(descripcion == null){
			descripcion = new HashMap<String, String>();
			cap.setDescripcion(descripcion);
		}*/
		
		HashMap<String,String> descripcion = new HashMap<String, String>();
		
		for(int i = 1; i<=10; i++){
			String key = (String)getServletRequest().getParameter("key_" + i);
			String value = getServletRequest().getParameter("value_" + i);
			if(key != null && !"".equals(key.trim())){
				descripcion.put(key, value);							
			}
		}
		
		cap.setDescripcion(descripcion);
	
		try {
			em.merge(cap);
		} finally {
			em.close();
		}
	
		return SUCCESS;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletResponse getServletResponse() {
		return response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletRequest getServletRequest() {
		return request;
	}

}
